package com.lun.blog.controller.admin;

import com.lun.blog.pojo.FriendLinks;
import com.lun.blog.service.FriendLinksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin/friendLinks")
public class FriendLinksController {
    @Autowired
    private FriendLinksService friendLinksService;

    @GetMapping("/redirectToFriendLinks")
    public String redirectToFriendLinks(@PageableDefault(size = 5,sort = {"id"},direction = Sort.Direction.DESC) Pageable pageable,
                                        Model model){
        model.addAttribute("page",friendLinksService.listPage(pageable));
        return "admin/friendlinks";
    }
    @GetMapping("/add")
    public String add(){
        return "admin/friendlinks-input";
    }

    @PostMapping("/saveFriendLinks")
    public String saveFriendLinks(FriendLinks friendLinks, RedirectAttributes attributes){
        FriendLinks byBlogName = friendLinksService.findByBlogName(friendLinks.getBlogName());
        if(byBlogName!=null){
            attributes.addFlashAttribute("message","友链已存在");
        }else {
            friendLinksService.saveFriendLinks(friendLinks);
            attributes.addFlashAttribute("message","保存"+friendLinks.getBlogName()+"成功");
        }
        return "redirect:/admin/friendLinks/redirectToFriendLinks";
    }

    @GetMapping("/deleteFriendLinks")
    public String deleteFriendLinks(String id,RedirectAttributes attributes){
        friendLinksService.deleteFriendLinks(Long.parseLong(id));
        attributes.addFlashAttribute("message","删除成功");
        return "redirect:/admin/friendLinks/redirectToFriendLinks";
    }

    @GetMapping("/updateFriendLinks")
    public String updateFriendLinks(String id,Model model){
        FriendLinks friendLinks = friendLinksService.getFriendLinks(Long.parseLong(id));
        model.addAttribute("friendLinks",friendLinks);
        return "admin/friendlinks-update";
    }
    @PostMapping("/updateFriendLinks")
    public String updateFriendLinks(FriendLinks friendLinks,RedirectAttributes attributes){
       friendLinksService.saveFriendLinks(friendLinks);
       attributes.addFlashAttribute("message","修改"+friendLinks.getBlogName()+"成功");
       return "redirect:/admin/friendLinks/redirectToFriendLinks";
    }
}
